package com.tom.rpc.v2;

import com.tom.RpcDiscover;
import com.tom.rpc.v2.common.RpcRequest;
import com.tom.rpc.v2.common.RpcResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author yanghongjun19
 * @date 2021/01/06
 **/

@Slf4j
public class RpcClient {
    private String host;
    private int port;
    private RpcDiscover rpcDiscover;

    public RpcClient(RpcDiscover rpcDiscover) {
        this.rpcDiscover = rpcDiscover;
    }

    /**
     * 发送rpc请求
     *
     * @param rpcRequest rpc请求bean
     * @return 请求回来的数据
     */
    public Object send(RpcRequest rpcRequest) {
        try {
            String discover = rpcDiscover.discover();
            log.info("发现的节点是:" + discover);
            String[] split = discover.split(":");
            host = split[0];
            port = Integer.valueOf(split[1]);
            Socket socket = new Socket(host, port);
            OutputStream outputStream = socket.getOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(rpcRequest);
            InputStream inputStream = socket.getInputStream();
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);

            RpcResponse rpcResponse = (RpcResponse) objectInputStream.readObject();
            log.info("服务端响应给客户端的请求结果: rpcResponse = " + rpcResponse);
            return rpcResponse.getResult();

        } catch (Exception e) {
            log.error("数据发送异常:" + e.getMessage());
        }

        return null;
    }
}
